package com.qdxwx.web.controller.book;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.data.service.favorite.FavoriteService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.models.book.Book;
import com.qdxwx.models.book.BookQuery;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Course接口
 * @author developer
 */
@Controller
@RequestMapping("/book")
public class BookViewController extends BaseController {

    @Autowired
    private BookService bookService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private FavoriteService favoriteService;

    @RequestMapping("/view/{id:[0-9]+}.html")
    public String index(@PathVariable("id") int id, HttpServletRequest request, ModelMap mmap) {
        long userId = LoginUser.getUserId(request);
        if (id < 1) return toError404(request);
        Book book = bookService.get(id);
        if (book == null) return toError404(request);
        BookQuery query = new BookQuery();
        query.setIsAvailable(1);
        query.setSubjectId(book.getSubjectId());
        List<Book> bookList = bookService.getList(query, new PageRequest(1, 6));
        if (userId > 0) {
            //查询是否已经收藏
            boolean isFavorite = favoriteService.isExist(userId, book.getId(), ModuleType.BOOK.ordinal());
            mmap.put("isFavorite", isFavorite);
        } else {
            mmap.put("isFavorite", false);
        }
        mmap.put("userId", userId);
        mmap.put("book", book);
        String description = TKString.clearIntro(book.getIntro());
        if (description.length()>120){
            description = description.substring(0, 120);
        }
        mmap.put("pageDescription", description);
        mmap.put("bookList", bookList);
        mmap.put("teachers", teacherService.getListByBookId(book.getId()));
        if (TKRequest.isMobileBrowse(request)) {
            return getViewPathH5("book/book-view");
        }
        return getViewPath("book/book-view");
    }

}
